package com.bifang.module.file.core.biz.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.assistant.common.constants.Validators;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.TreeUtil;
import com.bifang.module.base.common.vo.tree.TreeRetVO;
import com.bifang.module.base.common.vo.tree.TreeVO;
import com.bifang.module.file.common.vo.*;
import com.bifang.module.file.core.biz.FileClassMIntegration;
import com.bifang.module.file.dao.model.FileClass;
import com.bifang.module.file.dao.service.FileClassService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ApiService(funcCode = "fileClassM", title = "文件分类信息管理")
@Validated
public class FileClassMIntegrationImpl implements FileClassMIntegration {
    @Autowired
    FileClassService fileClassService;

    @Override
    @OpApi(funcCode = "fileClassM0001", title = "获取文件分类信息", funcType = FuncTypeEnum.query)
    public PageInfo<FileClassVO> getFileClassList(FileClassVO fileClassVO) {
        if (fileClassVO.getPageNum() != null && fileClassVO.getPageSize() != null) {
            PageHelper.startPage(fileClassVO.getPageNum(), fileClassVO.getPageSize());
        }
        Map<String,Object> map = Convert.toMap(String.class,Object.class,fileClassVO);
        map.forEach((key,val)->{
            if(val instanceof String){
                if(StringUtils.isBlank((String)val)){
                    map.put(key,null);
                }
            }
        });
        FileClass fileClass = Convert.convert(FileClass.class,map);
        QueryWrapper<FileClass> query = new QueryWrapper<>(fileClass);
        List<FileClass> list = fileClassService.list(query);
        if (CollectionUtils.isEmpty(list)) {
            return PagerUtil.createEmptyPagerInfo(
                    fileClassVO.getPageNum(), fileClassVO.getPageSize());
        }
        PageInfo<FileClass> resultPageInfo = new PageInfo<>(list);
        List<FileClassVO> voList = Convert.toList(FileClassVO.class, list);
        for(FileClassVO vo : voList){
            if(vo.getFileEnvId()!=null){

            }
        }
        return PagerUtil.parsePagerVo(voList, resultPageInfo);
    }

    @Override
    @OpApi(funcCode = "fileClassM0002", title = "新增文件分类信息", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "fileClassM0002",
            operationName = "新增文件分类信息",
            dataType = "fileClassCode",
            auType = AuTypeEnum.OTHER)
    @Transactional
    @Validated(value = {Validators.Add.class})
    public void addFileClass(@Valid FileClassEditVO editVO) {
        //判断是否存在主键
        if(!StringUtils.isEmpty(editVO.getFileClassCode())){
            //存在主键信息进行更新操作
            updateFileClass(editVO);
        }
        saveCheck(editVO,"add");
        FileClass fileClass = Convert.convert(FileClass.class,editVO);

        fileClass.setCreateName(SessionUtil.getUserId());
        fileClass.setUpdateName(SessionUtil.getUserId());
        fileClassService.save(fileClass);
    }

    public void saveCheck(FileClassEditVO editVO,String addOrUpdate){
        if(StringUtils.isEmpty(editVO.getClassTitle())){
            throw new AppException("分类标题不能为空");
        }
        if(StringUtils.isEmpty(editVO.getStatus())){
            throw new AppException("有效状态不能为空");
        }
        if(StringUtils.isEmpty(editVO.getFielderShow())){
            //默认不需要归档
            editVO.setFielderShow("0");
        }
        if(StringUtils.isEmpty(editVO.getEncryptionFlag())){
            //默认是否需要加密
            editVO.setEncryptionFlag("0");
        }
        if("add".equals(addOrUpdate)){
            //判断当前文件分类是否已经存在
            QueryWrapper<FileClass> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(FileClass::getClassTitle,editVO.getClassTitle());
            long count = fileClassService.count(queryWrapper);
            if(count>0){
                throw new AppException("分类"+editVO.getClassTitle()+"已存在");
            }
        }else{
            //判断当前文件分类是否已经存在
            QueryWrapper<FileClass> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(FileClass::getClassTitle,editVO.getClassTitle())
                    .ne(FileClass::getFileClassCode,editVO.getFileClassCode());
            long count = fileClassService.count(queryWrapper);
            if(count>0){
                throw new AppException("分类"+editVO.getClassTitle()+"已存在");
            }
        }

    }

    @Override
    @OpApi(funcCode = "fileClassM0003", title = "修改文件分类信息", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "fileClassM0003",
            operationName = "修改文件基础信息",
            dataType = "fileClassCode",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void updateFileClass(@Validated(value = {Validators.Edit.class}) FileClassEditVO editVO) {
        saveCheck(editVO,"update");
        QueryWrapper<FileClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FileClass::getFileClassCode,editVO.getFileClassCode());
        if(fileClassService.count(queryWrapper)>0){
            FileClass fileClass = Convert.convert(FileClass.class,editVO);
            fileClass.setUpdateName(SessionUtil.getUserId());
            fileClassService.updateById(fileClass);
        }else{
            throw new AppException(String.format("修改失败，不存在文件分类编号为%s的文件分类",editVO.getFileClassCode()));
        }

    }

    @Override
    @OpApi(funcCode = "fileClassM0004", title = "删除文件分类信息", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "fileClassM0004",
            operationName = "删除文件分类信息",
            dataType = "fileClassCode",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void deleteFileClass(FileClassKeyVO fileClassKeyVO) {
        if(StringUtils.isBlank(fileClassKeyVO.getFileClassCode())){
            throw new AppException("文件分类编号不能为空");
        }
        QueryWrapper<FileClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FileClass::getFileClassCode,fileClassKeyVO.getFileClassCode());
        if(fileClassService.count(queryWrapper)>0){
            fileClassService.removeById(fileClassKeyVO.getFileClassCode());
        }
    }

    @Override
    @OpApi(
            funcCode = "fileClassM0005",
            title = "获取文件分类树",
            funcType = FuncTypeEnum.query,
            publicFlag = BoolEnum.TRUE,
            savelog = false)
    public TreeRetVO getFileClassTreeAllList(FileClassTreeVO fileClassTreeVO) {
        boolean lazy=false;
        if(fileClassTreeVO.getLazy()!=null){
            lazy= fileClassTreeVO.getLazy();
        }
        String searchText = fileClassTreeVO.getSearchText();
        List<FileClass> fileClassList=new ArrayList<>();
        if(lazy){
            String parentKey = fileClassTreeVO.getParentKey();
            if(StringUtils.isBlank(parentKey)){
                QueryWrapper<FileClass> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().eq(FileClass::getParentCode,null);
                List<FileClass> list = fileClassService.list(queryWrapper);
                fileClassList.addAll(list);
            }else{
                QueryWrapper<FileClass> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().eq(FileClass::getParentCode,parentKey);
                List<FileClass> list = fileClassService.list(queryWrapper);
                fileClassList.addAll(list);
            }
        }else{
            QueryWrapper<FileClass> queryWrapper=new QueryWrapper<>();
            if(StringUtils.isNotBlank(searchText)){
                //判断是否为中文,中文按分类名称查询,其他按编码查询
                if(Validator.isChinese(searchText)){
                    queryWrapper.lambda().like(FileClass::getClassTitle,searchText);
                }else{
                    queryWrapper.lambda().like(FileClass::getFileClassCode,searchText);
                }
            }
            List<FileClass> list = fileClassService.list(queryWrapper);
            fileClassList.addAll(list);
        }
        TreeRetVO treeRetVO = new TreeRetVO();
        if (CollectionUtils.isEmpty(fileClassList)) {
            treeRetVO.setTreeList(new ArrayList<>());
            return treeRetVO;
        }
        List<TreeVO> antTreeVOS=new ArrayList<>();
        for(FileClass fileClass:fileClassList){
            TreeVO antTreeVO=new TreeVO();
            antTreeVO.setKey(fileClass.getFileClassCode());
            antTreeVO.setParentKey(fileClass.getParentCode());
            antTreeVO.setTitle(fileClass.getClassTitle());
            if(StringUtils.isNotBlank(searchText)){
                antTreeVO.setLoaded(true);
                antTreeVO.setExpanded(true);
            }else{
                antTreeVO.setLoaded(false);
                antTreeVO.setExpanded(false);
            }
            Map<String,Object> map =new HashMap<>();
            map.put("title","title");
            antTreeVO.setScopedSlots(map);
            antTreeVOS.add(antTreeVO);
        }
        if(lazy){
            treeRetVO.setTreeList(antTreeVOS);
            return treeRetVO;
        }
        treeRetVO.setTreeList(TreeUtil.constructTaskDTOToTree(antTreeVOS));
        return treeRetVO;
    }

    @Override
    @OpApi(funcCode = "fileClassM0006", title = "获取文件分类详情", funcType = FuncTypeEnum.query)
    @SaveOplog(
            operationType = "fileClassM0006",
            operationName = "获取文件分类详情",
            dataType = "fileClassCode",
            auType = AuTypeEnum.OTHER)
    public FileClassVO getFileInfo(FileClassKeyVO keyVO) {
        if(StringUtils.isEmpty(keyVO.getFileClassCode())){
            throw new AppException("文件分类id不能为空");
        }
        FileClass entity = fileClassService.getById(keyVO.getFileClassCode());
        if(ObjectUtils.isEmpty(entity)){
            throw new AppException("未查询文件分类的详细信息");
        }
        FileClassVO result = Convert.convert(FileClassVO.class, entity);
        //判断是否存在父级分类编码若存在则获取父级分类名称
        if(!StringUtils.isEmpty(result.getParentCode())){
            FileClass parentFileClass = fileClassService.getById(result.getParentCode());
            if(ObjectUtils.isNotEmpty(parentFileClass)){
                result.setParentClassTitle(parentFileClass.getClassTitle());
            }
        }
        return result;
    }
}
